
const db = require('db');
const { getTokenInof } = require('tools/token');

module.exports = async ctx => {
    const { connection, comply } = db.init();
    try {
        const userInfo = getTokenInof(ctx.header.authorization).userInfo;
        const userid = userInfo.userid;
        const orderNo = await getOrderNo(userid, comply)
        ctx.body = newName(orderNo);
        ctx.status = 200;
    } catch (error) {
        ctx.status = error.status;
        ctx.body = error.err;
    }
    connection.end();
}

async function getOrderNo(userid, comply) {
    try {
        return (await comply(`
            SELECT orderNo FROM orders 
            WHERE commercialSpecialistId = '${userid}' 
            ORDER BY orderTime DESC
            LIMIT 0, 1
        `))[0].orderNo
    } catch (error) {
        return undefined
    }
}

/**
 * @param {string} orderNo 
 * @returns 
 */
function newName(orderNo) {
    if (orderNo) {
        const i = parseInt(orderNo.split('-').pop());
        return `${i}` === 'NaN' ? 0 : i;
    } else {
        return 0
    }
}